package com.atsongyr.springcloud.controller;

import com.atsongyr.springcloud.service.PaymentHystrixService;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author
 * DefaultProperties 全局降级熔断，当服务需要降级时，调用此方法。
 */
@RestController
@Slf4j
@DefaultProperties(defaultFallback = "payment_Global_FallbackMethod")
public class OrderHystrixController {

    @Resource
    private PaymentHystrixService paymentHystrixService;

    @GetMapping("/consumer/payment/hystrix/ok/{id}")
    public String paymentInfo_OK(@PathVariable("id") Integer id) {
        String result = paymentHystrixService.paymentInfo_OK(id);
        return result;
    }


    /**
     * 超时测试熔断
     * fallbackMethod出问题后兜底的方法
     * HystrixProperty 意思为这个线程峰值为三秒，三秒以内走自己的业务逻辑，超过三秒走paymentInfo_TimeoutHandler
     * 当只添加@HystrixCommand，未指明降级兜底方法时，则调用类注解进行降级兜底@DefaultProperties(defaultFallback = "payment_Global_FallbackMethod")
     * @param id
     * @return
     */
    @GetMapping("/consumer/payment/hystrix/timeout/{id}")
//    @HystrixCommand(fallbackMethod = "paymentInfo_TimeoutHandler", commandProperties = {
//            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")})
    @HystrixCommand
    public String paymentInfo_Timeout(Integer id) {
        int sleepTime = 5;
        try {
            TimeUnit.SECONDS.sleep(sleepTime);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return "线程池："+Thread.currentThread().getName() + " paymentInfo_Timeout,id:"
                + id
                + "\t"+"耗时(秒)"+sleepTime;
    }

    public String paymentInfo_TimeoutHandler(Integer id){
        return "我是消费者80，对方支付系统繁忙，请10秒后在尝试或者自己运行出错，请检查。(/ω＼)";
    }

//    @GetMapping("/consumer/payment/hystrix/timeout/{id}")
//    public String paymentInfo_Timeout(@PathVariable("id") Integer id) {
//        String result = paymentHystrixService.paymentInfo_Timeout(id);
//        return result;
//    }

    /**
     * 下面是全局fallback
     */
    public String payment_Global_FallbackMethod() {
        return "Global 异常处理信息，请稍后再试。";
    }
}
